
import java.util.Stack;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author jy
 */
public class ReverseMaxMatching implements Segment {
    private int m_nMaxLength = 3;
    private StringBuilder m_result = new StringBuilder();
    private Stack<String> m_stack = new Stack<String>();
    
    
    public ReverseMaxMatching(){}
    public ReverseMaxMatching(int maxLength)
    {
        m_nMaxLength = maxLength;
    }
    
    public void segment(String str)
    {
        reverseMaxMatching(str, m_nMaxLength, str.length() -1);
        while(!m_stack.empty())
        {
            m_result.append(m_stack.pop());
        }
    }

    private void reverseMaxMatching(String str, int matchLength, int fromPosition)
    {
        if(fromPosition < 0)
            return;
        String tmp = null;
        if(fromPosition - matchLength >= 0)
        {
            //截取的长度不大于剩下串的长度
            tmp = str.substring(fromPosition-matchLength+1, fromPosition+1);
        }
        else
        {
            //长度不够了，截取剩下所有的
            tmp = str.substring(0, fromPosition+1);
        }
        
        if(Dic.matchWord(tmp))
        {
            //如果匹配成功。
            m_stack.push(tmp+"/ ");
            
            fromPosition-=matchLength;
            matchLength = m_nMaxLength;
            reverseMaxMatching(str, matchLength, fromPosition);
        }
        else
        {
            //匹配失败,1.减少串的长度。 2.字典中没有该词
            if(matchLength > 1)
            {
                matchLength-=1;
                reverseMaxMatching(str, matchLength, fromPosition);
            }
            else
            {
                //字典中无该词,直接添加这个词
                m_stack.push(" "+tmp);
                //递归调用
                fromPosition-=1;
                matchLength = m_nMaxLength;
                reverseMaxMatching(str, matchLength, fromPosition);
            }
        }
    }
    
    
    public String getResult()
    {
        return m_result.toString();
    }
    
    
}
